﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace Codemonk.Common.Configuring
{
    /// <summary>
    /// 读取器扩展
    /// </summary>
    public static class ConfigReaderExtensions
    {
        private static XmlNode CreateXmlNode(string xml)
        {
            if (string.IsNullOrWhiteSpace(xml)) return null;
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            return document;
        }
        public static XmlNode ReadAsNode(this IConfigReader reader, string xpath, string defaultValue = null)
        {
            var xml = ReadFirst(reader, xpath, defaultValue);
            return CreateXmlNode(xml);
        }
        public static string ReadFirst(this IConfigReader reader, string xpath, string defaultValue = null)
        {
            if (reader == null) return defaultValue;
            var obj = reader.Read(xpath);
            if (obj == null) return defaultValue;
            foreach (var item in obj)
                return item;
            return defaultValue;
        }
        public static IEnumerable<Tuple<string, string>> ReadDouble(this IConfigReader reader, string parnet, string first, string second)
        {
            var nodes = ReadComplex(reader, parnet);
            if (nodes == null) yield return null;
            foreach (var node in nodes)
            {
                var name = node.FirstChild.Name;
                var firstValue = node.ReadFirst(string.Concat(name, "/", first));
                var secondValue = node.ReadFirst(string.Concat(name, "/", second));
                yield return new Tuple<string, string>(firstValue, secondValue);
            }
        }
        public static IEnumerable<Tuple<string, string, string>> ReadTriple(this IConfigReader reader, string parnet, string first, string second, string third)
        {
            var nodes = ReadComplex(reader, parnet);
            if (nodes == null) yield return null;
            foreach (var node in nodes)
            {
                var name = node.FirstChild.Name;
                var firstValue = node.ReadFirst(string.Concat(name, "/", first));
                var secondValue = node.ReadFirst(string.Concat(name, "/", second));
                var thirdValue = node.ReadFirst(string.Concat(name, "/", third));
                yield return new Tuple<string, string, string>(firstValue, secondValue, thirdValue);
            }
        }

        public static IEnumerable<XmlNode> ReadComplex(this IConfigReader reader, string parnet)
        {
            var xml = reader.Read(parnet);
            if (xml == null) yield return null;
            foreach (var docuxml in xml)
                yield return CreateXmlNode(docuxml);
        }
    }
}
